<template>
<div>
  <van-address-edit
    :area-list="areaList"
    :show-delete="addressInfo.id"
    :show-set-default="addressInfo.id"
    :area-columns-placeholder="['请选择', '请选择', '请选择']"
    @save="onSave"
    @delete="onDelete"
    :address-info="{...addressInfo}"
  />
</div>
</template>

<script>

import { addAddress, editAddress, getAddressDetail, removeAddress } from '@/api/address'
import { areaList } from '@vant/area-data'

export default {
  name: 'addressIndex',
  data () {
    return {
      addressInfo: {},
      areaList: areaList
    }
  },
  methods: {
    onSave (content) {
      this.saveAddress(content)
      this.$router.push('/address')
    },
    onDelete (content) {
      this.deleteAddress(content.id)
      this.$router.push('/address')
    },
    async getAddressDetail (addressId) {
      const { data: { detail } } = await getAddressDetail(addressId)
      this.addressInfo.id = detail.address_id
      this.addressInfo.name = detail.name
      this.addressInfo.tel = detail.phone
      this.addressInfo.province = detail.region.province
      this.addressInfo.city = detail.region.city
      this.addressInfo.country = detail.region.region
      this.addressInfo.addressDetail = detail.detail
      // 临时
      this.addressInfo.areaCode = detail.region_id
    },
    async saveAddress (address) {
      const region = []
      region.push({ value: address.areaCode.substr(0, 2) + '0000', label: address.province })
      region.push({ value: address.areaCode.substr(0, 4) + '00', label: address.city })
      region.push({ value: address.areaCode, label: address.country })
      if (address.id) {
        await editAddress(address.id, address.name, address.tel, region, address.addressDetail)
      } else {
        await addAddress(address.name, address.tel, region, address.addressDetail)
      }
    },
    async deleteAddress (addressId) {
      await removeAddress(addressId)
    }
  },
  created () {
    const addressId = this.$route.params.id
    if (addressId) {
      this.getAddressDetail(addressId)
    }
  }
}
</script>

<style scoped>

</style>
